<?php
declare (strict_types = 1);

namespace app\api\model;

/**
 * @mixin \think\Model
 */
class Personnel extends BaseModel
{
    protected $table = 'evt_personnels';

    protected $hidden = ['password'];

    public function user()
    {
        return $this->hasOne(User::class, 'id' ,'user_id');
    }

    public function edit($data = [], &$error = '', $is_sql = false)
    {
        // 基础参数设置
        $id = isset($data[$this->getPk()]) ? (int)$data[$this->getPk()] : 0;
        //如果账号不存在则创建账号
        if(!$id) {
            if (self::where('phone', $data['phone'])->count() > 0)
            {
                $error = '人员已存在';
                return null;
            }
            
            $userdata = [
                'username' => ($data['phone'] != null) ? $data['phone'] : $data['name'],
                'password' => get_password('123456')
            ];
            $user = $this->user()->save($userdata);
    
            if($user)
            {
                $data['user_id'] = $user->id;
            }
        }

        return parent::edit($data, $error, $is_sql);
    }
    
}
